package com.bwie.service.impl;

import cn.hutool.core.util.IdUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.bwie.mapper.*;
import com.bwie.poi.Excel;
import com.bwie.poi.ExcelUtil;
import com.bwie.pojo.*;
import com.bwie.service.TbOrderService;
import com.bwie.utils.Result;
import com.bwie.vo.PageInfoVo;
import io.jsonwebtoken.Claims;
import io.jsonwebtoken.Jwts;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;

/**
* @author 28242
* @description 针对表【tb_order(订单表)】的数据库操作Service实现
* @createDate 2025-05-30 09:27:51
*/
@Service
@Transactional(rollbackFor = Exception.class)
public class TbOrderServiceImpl extends ServiceImpl<TbOrderMapper, TbOrder>
    implements TbOrderService{

    @Autowired
    HttpServletRequest request;

    @Autowired
    TbProdInfoMapper tbProdInfoMapper;
    @Autowired
    TbOrderDetailMapper tbOrderDetailMapper;

    @Autowired
    TbProdMapper tbProdMapper;


    @Autowired
    TbOrderMapper tbOrderMapper;

    @Autowired
    TbProdImageMapper tbProdImageMapper;

    @Autowired
    HttpServletResponse response;

    @Override
    public Result addOrder(List<TbProdInfo> prodInfoList) {

        //获取用户信息
        String token = request.getHeader("token");
        if (token==null){
            return Result.error().setMsg("token");
        }

        Claims body = Jwts.parser().setSigningKey("123456").parseClaimsJws(token).getBody();
        Integer userId = body.get("userId", Integer.class);
        String userName = body.get("userName", String.class);
        String nickName = body.get("nickName", String.class);


        BigDecimal amount=new BigDecimal(0.0);
        StringBuilder nameList = new StringBuilder();
        Integer total=0;
        //判断库存
        for (TbProdInfo tbProdInfo : prodInfoList) {

            TbProdInfo prodInfo = tbProdInfoMapper.selectById(tbProdInfo.getInfoId());
            if (tbProdInfo.getBuyNum() >tbProdInfo.getProdStock()){
//                return Result.error().setMsg("库存不足");
                throw new RuntimeException("库存不足");
            }else {
                prodInfo.setProdStock(prodInfo.getProdStock()-tbProdInfo.getBuyNum());

                tbProdInfoMapper.updateById(prodInfo);
            }



            TbProd tbProd = tbProdMapper.selectById(prodInfo.getProdId());

            if (nameList.length()==0){
                nameList.append(tbProd.getProdName()).append(prodInfo.getAttrColor());
            }
            else {
                nameList.append("").append(tbProd.getProdName()).append(prodInfo.getAttrColor());
            }

            total+=tbProdInfo.getBuyNum();

            TbOrder tbOrder = new TbOrder();
            tbOrder.setUserId(userId);
            tbOrder.setCreateBy(nickName);
            tbOrder.setCreateTime(new Date());

            long orderNo = IdUtil.getSnowflake(1, 1).nextId();
            System.out.println("订单id"+orderNo);

            tbOrder.setOrderNo(orderNo);

            amount=prodInfo.getProdPrice().multiply(new BigDecimal(tbProdInfo.getBuyNum())).add(amount);
            tbOrder.setAmount(amount);

            tbOrder.setOrderStatus(0);
            tbOrder.setOrderType(0);
            tbOrder.setCoupon(0);
            tbOrder.setDelivery("");
            tbOrder.setProdInfo(nameList.toString());

            tbOrder.setProdNum(total);

            tbOrder.setUserScore(0);

            tbOrderMapper.insert(tbOrder);

            for (TbProdInfo info : prodInfoList) {
                TbOrderDetail tbOrderDetail = new TbOrderDetail();

                tbOrderDetail.setOrderId(tbOrder.getOrderId());
                tbOrderDetail.setProdId(info.getProdId());
                tbOrderDetail.setProdNum(info.getBuyNum());
                tbOrderDetail.setProdPrice(tbProdInfo.getProdPrice());

                tbOrderDetailMapper.insert(tbOrderDetail);
            }

        }

        return Result.ok();
    }

    @Override
    public Result getOrderList(PageInfoVo pageInfoVo) {

        Page<TbOrder> page = new Page<>(pageInfoVo.getPageNum(),pageInfoVo.getPageSize());

//        QueryWrapper<TbOrder> wrapper = new QueryWrapper<>();
//        wrapper.lambda().orderByDesc(TbOrder::getCreateTime);
        Page<TbOrder> tbOrderPage = tbOrderMapper.getOrderList(page,pageInfoVo);

        tbOrderPage.getRecords().forEach(tbOrder -> {
            List<TbOrderDetail> tbOrderDetails = tbOrderDetailMapper.selectList(
                    new QueryWrapper<TbOrderDetail>().lambda().eq(TbOrderDetail::getOrderId, tbOrder.getOrderId())
            );
            tbOrderDetails.forEach(tbOrderDetail -> {
                List<TbProdImage> tbProdImages = tbProdImageMapper.selectList(
                        new QueryWrapper<TbProdImage>().lambda().eq(TbProdImage::getProdId, tbOrderDetail.getProdId())
                );
                tbOrderDetail.setImageList(tbProdImages.stream().map(item->item.getImageUrl()).collect(Collectors.toList()));

                tbOrder.setImageList(tbProdImages.stream().map(item->item.getImageUrl()).collect(Collectors.toList()));
            });
            tbOrder.setOrderDetailList(tbOrderDetails);
        });

        return Result.ok().setData(tbOrderPage);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public Result deleteAll(List<TbOrder> orders) {

        //判断订单是否存在
        for (TbOrder order : orders) {
            TbOrder tbOrder = tbOrderMapper.selectById(order.getOrderId());
            if (tbOrder==null){
                throw new RuntimeException("订单不存在");
            }

            tbOrderDetailMapper.delete(
                    new QueryWrapper<TbOrderDetail>().lambda().eq(TbOrderDetail::getOrderId,order.getOrderId())
            );


            tbOrderMapper.deleteById(order.getOrderId());

        }





        return Result.ok();
    }

    @Override
    public void ExportExcel(String ids) {

        String[] split = ids.split(",");
        ArrayList<Integer> integers = new ArrayList<>();
        for (String s : split) {
            integers.add(Integer.valueOf(s));
        }

        List<TbOrder> tbOrders = tbOrderMapper.selectBatchIds(integers);

        ExcelUtil<TbOrder> excelUtil = new ExcelUtil<TbOrder>(TbOrder.class);

        excelUtil.exportExcel(response,tbOrders,"订单列表");


    }


}




